package me.hys.service.company.impl;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

import me.hys.base.PageQuery;
import me.hys.dao.company.IProductMapper;
import me.hys.entity.company.ProductEntity;
import me.hys.service.company.IProductManager;
import me.hys.service.system.IDeviceTokenManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Maps;

@Service
@Transactional
class ProductManagerImpl implements IProductManager {
	@Autowired
	private IProductMapper productMapper;
	@Autowired
	private IDeviceTokenManager deviceTokenManager;

	/*
	 * (non-Javadoc)
	 * 
	 * @see me.hys.base.IBaseManager#delete(java.lang.String)
	 */
	@Override
	public void delete(String id) {
		productMapper.delete(id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see me.hys.base.IBaseManager#findByCond(java.util.Map)
	 */
	@Override
	public List<ProductEntity> findByCond(Map<String, Object> cond) {
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see me.hys.service.company.IProductManager#findById(java.util.Map)
	 */
	@Override
	public ProductEntity findById(Map<String, Object> params) {
		return productMapper.findByParams(params);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see me.hys.base.IBaseManager#findById(java.lang.String)
	 */
	@Override
	public ProductEntity findById(String id) {
		return productMapper.findById(id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see me.hys.service.company.IProductManager#findLatest()
	 */
	@Override
	public ProductEntity findLatest() {
		return productMapper.findLatest();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see me.hys.base.IBaseManager#findPage(me.hys.base.PageQuery)
	 */
	@Override
	public PageQuery<ProductEntity> findPage(PageQuery<ProductEntity> page) {
		page.setList(productMapper.findAll(page.getCondition()));
		page.setTotal(productMapper.findAllCount(page.getCondition()));
		// 总页数
		int size = (int) Math.ceil(page.getTotal() * 1.0f / page.getLimit());
		page.setSize(size);
		return page;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see me.hys.service.company.IProductManager#push(java.lang.String)
	 */
	@Override
	public void push(String id) {
		ProductEntity entity = findById(id);
		if (null != entity) {
			Map<String, Object> params = Maps.newHashMap();
			params.put("id", id);
			params.put("type", "product");
			deviceTokenManager.push(entity.getTitle(), params);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see me.hys.base.IBaseManager#saveOrUpdate(java.lang.Object)
	 */
	@Override
	public int saveOrUpdate(ProductEntity entity) {
		if (entity.getId() > 0) {
			return productMapper.update(entity);
		} else {
			entity.setPubtime(new Timestamp(System.currentTimeMillis()));
			productMapper.save(entity);
			return entity.getId();
		}
	}
}
